package com.ray.export.runner.exports;

import com.ray.export.empty.Empty;
import com.ray.export.runner.Runner;
import com.ray.export.runner.RunnerResult;
import com.ray.export.spring.ApplicationContextUtil;
import com.ray.export.strategy.data.DataModel;
import com.ray.export.strategy.exports.ExportFileStore;
import com.ray.export.strategy.file.FileResult;
import com.ray.export.template.ExportTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

/**
 * <p>ClassName:     ExportFileStoreRunner
 * <p>Description:   导出文件存储执行者
 * <p>Author         jumWang
 * <p>Version        V1.0
 * <p>Date           2019.12.5
 */
@Slf4j
public class ExportFileStoreRunner implements Runner<ExportTemplate> {

    @Override
    public RunnerResult doRunner(ExportTemplate annotation, DataModel dataModel, RunnerResult perResult) {
        log.info("执行导出文件存储方法");
        Class<?> exportFileStoreClass = annotation.exportFileStore();
        if (exportFileStoreClass == Empty.class) {
            return new RunnerResult(Empty.class, dataModel,dataModel.getBeforeResult());
        }
        if(!dataModel.isAsynchronou() || StringUtils.isEmpty(dataModel.getTmpFilePath())) {
            return new RunnerResult(Empty.class, dataModel,dataModel.getBeforeResult());
        }
        //判读配置是否符合规则
        if (!ExportFileStore.class.isAssignableFrom(exportFileStoreClass)) {
            log.error("导出文件存储配置错误");
            throw new RuntimeException("导出文件存储配置错误");
        }
        //获取执行对象
        ExportFileStore exportFileStore = (ExportFileStore) ApplicationContextUtil.getApplicationContext().getBean(exportFileStoreClass);
        if (ObjectUtils.isEmpty(exportFileStore)) {
            log.error("获取执行对象异常[{}]", exportFileStoreClass.getName());
            throw new RuntimeException("获取执行对象异常");
        }
        FileResult fileResult = exportFileStore.saveFile(dataModel.getTmpFilePath());
        if (ObjectUtils.isEmpty(fileResult)) {
            log.error("文件存储失败");
            throw new RuntimeException("文件存储失败");
        }
        dataModel.setTaskKey(fileResult.getUrl());
        return new RunnerResult(ExportFileStore.class, dataModel, fileResult);
    }

}
